<script setup lang="ts" name="ResetPasswordForm">
import { useIcon } from '@/hooks/web/useIcon'
import { setTenantIdCache } from '@/utils/auth'
import { AuthApi } from '@/api/auth'
import LoginFormTitle from './LoginFormTitle.vue'
import { LoginStateEnum, useFormValid, useLoginState } from './useLogin'

const { t } = useI18n()
const message = useMessage()
const iconHouse = useIcon({ icon: 'ep:house' })
// const iconEMail = useIcon({ icon: 'ep:message' })
const iconCellphone = useIcon({ icon: 'ep:cellphone' })
const iconLock = useIcon({ icon: 'ep:lock' })
const iconCircleCheck = useIcon({ icon: 'ep:circle-check' })
const formLogin = ref()
const { validForm } = useFormValid(formLogin)
const { handleBackLogin, getLoginState } = useLoginState()
// const loginLoading = ref(false)

const getShow = computed(() => unref(getLoginState) === LoginStateEnum.RESET_PASSWORD)


const rules = {
  tenantName: [required],
  mobileNumber: [required],
  // email: [required],
  code: [required],
  password: [required],
  check_password: [required]
}

const resetPasswordData = reactive({
  tenantEnable: import.meta.env.VITE_APP_TENANT_ENABLE,
  form: {
    tenantName: import.meta.env.VITE_APP_DEFAULT_LOGIN_TENANT || '',
    mobileNumber: '',
    // email: '',
    code: '',
    password: '',
    check_password: ''
  }
})

const smsInfo = reactive({
  smsCode: {
    mobile: '',
    scene: 21
  }
})

const mobileCodeTimer = ref(0)
const getSmsCode = async () => {
  await getTenantId()
  smsInfo.smsCode.mobile = resetPasswordData.form.mobileNumber
  await AuthApi.Sms.code(smsInfo.smsCode).then(async () => {
    message.success(t('sign.fields.code', 'send'))
    // 设置倒计时
    mobileCodeTimer.value = 60
    let msgTimer = setInterval(() => {
      mobileCodeTimer.value = mobileCodeTimer.value - 1
      if (mobileCodeTimer.value <= 0) {
        clearInterval(msgTimer)
      }
    }, 1000)
  })
}

// 获取租户 ID
const getTenantId = async () => {
  if (resetPasswordData.tenantEnable === 'true') {
    const res = await AuthApi.Tenant.getIdByName(resetPasswordData.form.tenantName)
    setTenantIdCache(res)
  }
}

const loading = ref(false)
// 重置密码
const reset = async () => {
  await getTenantId()
  const data = await validForm()
  if (!data) return
  try {
    loading.value = true
    await AuthApi.resetPassword(resetPasswordData.form)
    .then(async () => {
      message.success(t('sign.fields.reset', 'success'))
    })
    .catch(() => {})
  } finally {
    loading.value = false
  }

}
</script>

<template>
  <el-form v-show="getShow" ref="formSmsLogin" :model="resetPasswordData.form" :rules="rules" class="login-form" label-position="top" label-width="120px" size="large">
    <el-row>
      <!-- 租户名 -->
      <el-col :span="24">
        <el-form-item>
          <LoginFormTitle style="width: 100%" />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item v-if="resetPasswordData.tenantEnable === 'true'" prop="tenantName">
          <el-input v-model="resetPasswordData.form.tenantName" :placeholder="t('sign.fields.tenant', 'placeholder')" :prefix-icon="iconHouse" type="primary" link />
        </el-form-item>
      </el-col>
      <!-- 手机号 -->
      <el-col :span="24" class="mt-[12px]">
        <el-form-item prop="mobileNumber">
          <el-input v-model="resetPasswordData.form.mobileNumber" :placeholder="t('sign.fields.phone', 'placeholder')" :prefix-icon="iconCellphone" />
        </el-form-item>
      </el-col>
      <!-- 邮箱 -->
      <!-- <el-col :span="24" class="mt-[12px]">
        <el-form-item prop="email">
          <el-input
            v-model="resetPasswordData.form.email"
            :placeholder="t('sign.fields.email', 'placeholder')"
            :prefix-icon="iconEMail"
          />
        </el-form-item>
      </el-col> -->
      <!-- 验证码 -->
      <el-col :span="24" class="mt-[12px]">
        <el-form-item prop="code">
          <el-input v-model="resetPasswordData.form.code" :placeholder="t('sign.fields.code', 'placeholder')" :prefix-icon="iconCircleCheck">
            <template #append>
              <span v-if="mobileCodeTimer <= 0" class="getMobileCode" style="cursor: pointer" @click="getSmsCode">
                {{ t('sign.fields.code', 'button') }}
              </span>
              <span v-if="mobileCodeTimer > 0" class="getMobileCode" style="cursor: pointer">
                {{ t('sign.fields.code', 'restart', [mobileCodeTimer]) }}
              </span>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <!-- 新密码 -->
      <el-col :span="24" class="mt-[12px]">
        <el-form-item prop="password">
          <InputPassword v-model="resetPasswordData.form.password" :placeholder="t('sign.fields.password', 'placeholder')" :prefix-icon="iconLock" strength style="width: 100%;" />
        </el-form-item>
      </el-col>
      <!-- 确认密码 -->
      <el-col :span="24" class="mt-[12px]">
        <el-form-item prop="check_password">
          <InputPassword v-model="resetPasswordData.form.check_password" :placeholder="t('sign.fields.password', 'placeholderTwice')" :prefix-icon="iconLock" strength style="width: 100%;" />
        </el-form-item>
      </el-col>
      <!-- 重置密码按钮 / 返回按钮 -->
      <el-col :span="24" class="mt-[12px]">
        <el-form-item>
          <CButton :loading="loading" :title="t('sign.reset', 'action')" class="w-[100%]" type="primary" @click="reset()" />
        </el-form-item>
      </el-col>
      <el-col :span="24" class="mt-[12px]">
        <el-form-item>
          <CButton :title="t('sign', 'backLogin')" class="other-button w-[100%]" @click="handleBackLogin()" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<style scoped lang="scss"></style>
